/**
 * Copyright (c) 2016 Lenovo Group
 * All Rights Reserved.
 * 
 * Project Name:event-recorder
 * Create Time: 2016年4月28日 下午3:06:54
 */
package com.lenovo.lmrp.server.eventrecorder.domain.ticket;

import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.lenovo.sdc.framework.util.exception.ErrorCode;
import com.lenovo.sdc.framework.util.exception.TraceableException;

/**
 * @author zhangzheng
 *
 */
public abstract class BatchWriter<T> extends Thread {
    
    private Queue<T> queue;
    
    public BatchWriter() {
        this.queue = new ConcurrentLinkedQueue<T>();
    }
    
    public abstract void batchStore(List<T> poList);
    
    public void push(T po) {
        queue.add(po);
    }
    @Override
    public void run() {
        while(!isInterrupted()) {
            try {
                synchronized (queue) {
                    queue.wait(3000);
                }
                // dump queued po to temparate list;
                List<T> datas = new ArrayList<>(64);
                int i = 0;
                T po = null;
                while ((po = queue.poll()) != null && i <= 128) {
                    datas.add(po);
                    i ++;
                }
                if(datas.isEmpty())
                    continue;
                
                // batch to cassandra datastore
                this.batchStore(datas);
            }
            catch (InterruptedException exp) {
                return;
            }
            catch(Exception exp) {
                TraceableException.writeLog(ErrorCode.DB_INSERT_FAILED, "", exp);
            }
        }
    }
    
}
